from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework import status
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from django.db import transaction
import json
from datetime import datetime

from .models import SysRole, SysPermission, SysRolePermission, SysUserRole
from user.models import SysUser


class RoleListView(APIView):
    """
    角色列表视图类
    处理角色列表查询请求，支持分页、搜索
    """
    permission_classes = [AllowAny]

    def get(self, request):
        """
        处理GET请求获取角色列表
        :param request: 包含查询参数的请求
        :return: 角色列表数据
        """
        try:
            # 获取查询参数
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            name = request.GET.get('name', '')
            status_filter = request.GET.get('status', '')
            
            # 构建查询条件
            query = Q()
            
            if name:
                query &= Q(name__icontains=name)
            
            if status_filter == 'active':
                query &= Q(status=0)
            elif status_filter == 'inactive':
                query &= Q(status=1)
            
            # 查询角色列表
            roles = SysRole.objects.filter(query).order_by('sort', 'id')
            
            # 分页处理
            paginator = Paginator(roles, page_size)
            try:
                current_page = paginator.page(page)
            except PageNotAnInteger:
                current_page = paginator.page(1)
            except EmptyPage:
                current_page = paginator.page(paginator.num_pages)
            
            # 构建返回数据
            roles_data = []
            for role in current_page:
                roles_data.append({
                    'id': role.id,
                    'name': role.name,
                    'description': role.description,
                    'sort': role.sort,
                    'status': role.status,
                    'is_active': role.status == 0,
                    'created_at': role.create_time.strftime('%Y-%m-%d %H:%M:%S') if role.create_time else '',
                    'remark': role.remark
                })
            
            return Response({
                'code': 200,
                'message': '获取角色列表成功',
                'data': {
                    'results': roles_data,
                    'count': paginator.count,
                    'page': page,
                    'page_size': page_size,
                    'total_pages': paginator.num_pages
                }
            })
            
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取角色列表失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class RoleCreateView(APIView):
    """
    角色创建视图类
    处理新增角色请求
    """
    permission_classes = [AllowAny]

    def post(self, request):
        """
        处理POST请求创建新角色
        :param request: 包含角色信息的请求
        :return: 创建结果
        """
        try:
            # 获取请求数据
            if hasattr(request, 'data'):
                data = request.data
            else:
                if request.content_type == 'application/json':
                    data = json.loads(request.body.decode('utf-8'))
                else:
                    data = request.POST
            
            name = data.get('name')
            description = data.get('description')
            sort = data.get('sort', 0)
            permissions = data.get('permissions', [])
            
            # 数据验证
            if not name:
                return Response({
                    'code': 400,
                    'message': '角色名称不能为空'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 检查角色名称是否已存在
            if SysRole.objects.filter(name=name).exists():
                return Response({
                    'code': 400,
                    'message': '角色名称已存在'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 使用事务创建角色和权限关联
            with transaction.atomic():
                # 创建角色
                role = SysRole.objects.create(
                    name=name,
                    description=description,
                    sort=sort,
                    status=0
                )
                
                # 创建角色权限关联
                if permissions:
                    for permission_id in permissions:
                        try:
                            permission = SysPermission.objects.get(id=permission_id)
                            SysRolePermission.objects.create(role=role, permission=permission)
                        except SysPermission.DoesNotExist:
                            continue
            
            return Response({
                'code': 200,
                'message': '角色创建成功',
                'data': {
                    'id': role.id,
                    'name': role.name,
                    'description': role.description,
                    'sort': role.sort,
                    'status': role.status
                }
            })
            
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'角色创建失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class RoleUpdateView(APIView):
    """
    角色更新视图类
    处理角色信息更新请求
    """
    permission_classes = [AllowAny]

    def put(self, request, role_id):
        """
        处理PUT请求更新角色信息
        :param request: 包含角色信息的请求
        :param role_id: 角色ID
        :return: 更新结果
        """
        try:
            # 获取角色对象
            role = SysRole.objects.get(id=role_id)
            
            # 获取请求数据
            if hasattr(request, 'data'):
                data = request.data
            else:
                if request.content_type == 'application/json':
                    data = json.loads(request.body.decode('utf-8'))
                else:
                    data = request.POST
            
            name = data.get('name')
            description = data.get('description')
            sort = data.get('sort')
            permissions = data.get('permissions', [])
            
            # 数据验证
            if name and name != role.name:
                if SysRole.objects.filter(name=name).exists():
                    return Response({
                        'code': 400,
                        'message': '角色名称已存在'
                    }, status=status.HTTP_400_BAD_REQUEST)
            
            # 使用事务更新角色和权限关联
            with transaction.atomic():
                # 更新角色信息
                if name:
                    role.name = name
                if description is not None:
                    role.description = description
                if sort is not None:
                    role.sort = sort
                
                role.save()
                
                # 更新角色权限关联
                if permissions is not None:
                    # 先删除原有权限
                    SysRolePermission.objects.filter(role=role).delete()
                    
                    # 再添加新权限
                    for permission_id in permissions:
                        try:
                            permission = SysPermission.objects.get(id=permission_id)
                            SysRolePermission.objects.create(role=role, permission=permission)
                        except SysPermission.DoesNotExist:
                            continue
            
            return Response({
                'code': 200,
                'message': '角色信息更新成功',
                'data': {
                    'id': role.id,
                    'name': role.name,
                    'description': role.description,
                    'sort': role.sort,
                    'status': role.status
                }
            })
            
        except SysRole.DoesNotExist:
            return Response({
                'code': 404,
                'message': '角色不存在'
            }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'角色信息更新失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class RoleDeleteView(APIView):
    """
    角色删除视图类
    处理角色删除请求
    """
    permission_classes = [AllowAny]

    def delete(self, request, role_id):
        """
        处理DELETE请求删除角色
        :param request: 请求对象
        :param role_id: 角色ID
        :return: 删除结果
        """
        try:
            # 获取角色对象
            role = SysRole.objects.get(id=role_id)
            
            # 检查是否有用户使用该角色
            if SysUserRole.objects.filter(role=role).exists():
                return Response({
                    'code': 400,
                    'message': '该角色下有用户，不能删除'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 使用事务删除角色和相关数据
            with transaction.atomic():
                # 删除角色权限关联
                SysRolePermission.objects.filter(role=role).delete()
                # 删除角色
                role.delete()
            
            return Response({
                'code': 200,
                'message': '角色删除成功'
            })
            
        except SysRole.DoesNotExist:
            return Response({
                'code': 404,
                'message': '角色不存在'
            }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'角色删除失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class PermissionListView(APIView):
    """
    权限列表视图类
    处理权限列表查询请求，返回树形结构
    """
    permission_classes = [AllowAny]

    def get(self, request):
        """
        处理GET请求获取权限列表
        :param request: 请求对象
        :return: 权限树形结构数据
        """
        try:
            # 获取所有权限
            permissions = SysPermission.objects.filter(status=0).order_by('sort', 'id')
            
            # 构建权限树
            def build_permission_tree(permissions_list, parent_id=0):
                tree = []
                for permission in permissions_list:
                    if permission.parent_id == parent_id:
                        children = build_permission_tree(permissions_list, permission.id)
                        node = {
                            'id': permission.id,
                            'label': permission.name,
                            'code': permission.code,
                            'type': permission.type,
                            'path': permission.path,
                            'icon': permission.icon,
                            'component': permission.component,
                            'sort': permission.sort,
                            'children': children if children else None
                        }
                        tree.append(node)
                return tree
            
            permission_tree = build_permission_tree(list(permissions))
            
            return Response({
                'code': 200,
                'message': '获取权限列表成功',
                'data': permission_tree
            })
            
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取权限列表失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class RolePermissionsView(APIView):
    """
    角色权限视图类
    处理获取角色权限请求
    """
    permission_classes = [AllowAny]

    def get(self, request, role_id):
        """
        处理GET请求获取角色权限
        :param request: 请求对象
        :param role_id: 角色ID
        :return: 角色权限列表
        """
        try:
            # 获取角色对象
            role = SysRole.objects.get(id=role_id)
            
            # 获取角色权限
            role_permissions = SysRolePermission.objects.filter(role=role)
            permission_ids = [rp.permission.id for rp in role_permissions]
            
            return Response({
                'code': 200,
                'message': '获取角色权限成功',
                'data': {
                    'role_id': role.id,
                    'role_name': role.name,
                    'permission_ids': permission_ids
                }
            })
            
        except SysRole.DoesNotExist:
            return Response({
                'code': 404,
                'message': '角色不存在'
            }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取角色权限失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class UserRoleView(APIView):
    """
    用户角色管理视图类
    处理用户角色分配请求
    """
    permission_classes = [AllowAny]

    def post(self, request):
        """
        处理POST请求分配用户角色
        :param request: 包含用户和角色信息的请求
        :return: 分配结果
        """
        try:
            # 获取请求数据
            if hasattr(request, 'data'):
                data = request.data
            else:
                if request.content_type == 'application/json':
                    data = json.loads(request.body.decode('utf-8'))
                else:
                    data = request.POST
            
            user_id = data.get('user_id')
            role_ids = data.get('role_ids', [])
            
            # 数据验证
            if not user_id:
                return Response({
                    'code': 400,
                    'message': '用户ID不能为空'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 检查用户是否存在
            try:
                user = SysUser.objects.get(id=user_id)
            except SysUser.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '用户不存在'
                }, status=status.HTTP_404_NOT_FOUND)
            
            # 使用事务更新用户角色
            with transaction.atomic():
                # 先删除用户原有角色
                SysUserRole.objects.filter(user_id=user_id).delete()
                
                # 再添加新角色
                for role_id in role_ids:
                    try:
                        role = SysRole.objects.get(id=role_id)
                        SysUserRole.objects.create(user_id=user_id, role=role)
                    except SysRole.DoesNotExist:
                        continue
            
            return Response({
                'code': 200,
                'message': '用户角色分配成功',
                'data': {
                    'user_id': user_id,
                    'username': user.username,
                    'role_ids': role_ids
                }
            })
            
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'用户角色分配失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
